﻿using System;
using System.Collections.Generic;
using System.Linq;
using Caliburn.Micro;
using JY.Wpf.Core.ViewModelBases;

namespace JY.Wpf.Core.Tools
{
    /// <summary>
    /// 事件扩展类
    /// </summary>
    public static class EventAggregatorExtension
    {
        /// <summary>
        /// 订阅者集合
        /// </summary>
        /// <remarks>订阅者 是否独占</remarks>
        private static readonly Dictionary<ViewModelBase,bool> EventSubscribers=new Dictionary<ViewModelBase, bool>();

        #region # 扩展注册事件
        /// <summary>
        /// 扩展注册事件
        /// </summary>
        /// <param name="eventAggregator">事件聚合器</param>
        /// <param name="subscriber">订阅者</param>
        /// <param name="isAlone">是否独占</param>
        public static void Subscribe(this IEventAggregator eventAggregator, ViewModelBase subscriber, bool isAlone)
        {
            if (subscriber == null) return;
            eventAggregator.Subscribe(subscriber);
            if (EventSubscribers.All(x => x.Key.GetType()!= subscriber.GetType()))
            {
                EventSubscribers.Add(subscriber, isAlone);
            }
            else
            {
                var subscribers=EventSubscribers.Keys.ToList();
                for (int i = 0; i < subscribers.Count; i++)
                {
                    if (subscribers[i].GetType() == subscriber.GetType())
                    {
                        EventSubscribers.Remove(subscribers[i]);
                    }
                }
                EventSubscribers.Add(subscriber, isAlone);
            }
        }
        #endregion

        #region # 取消注册事件
        /// <summary>
        /// 取消注册事件
        /// </summary>
        /// <param name="eventAggregator">事件聚合器</param>
        /// <param name="subscriber">订阅者</param>
        public static void UnSubscribe(this IEventAggregator eventAggregator, ViewModelBase subscriber)
        {
            if (EventSubscribers.Any(x => x.Key == subscriber))
            {
                EventSubscribers.Remove(subscriber);
            }
            eventAggregator.Unsubscribe(subscriber);
        }
        #endregion

        #region # 检测事件是否可执行
        /// <summary>
        /// 检测事件是否可执行
        /// </summary>
        /// <param name="subscriber">订阅者</param>
        /// <param name="eventType">事件类型</param>
        public static bool CheckCanPublishSubscriber(ViewModelBase subscriber,Type eventType)
        {
            IEnumerable<KeyValuePair<ViewModelBase, bool>> subscribers = EventSubscribers.Where(x => x.Key!=subscriber&& eventType.IsAssignableFrom(x.Key.GetType()));
            if (subscribers.Any()&& subscribers.Any(x=>x.Value))
            {
                return false;
            }

            return true;
        }
        #endregion
    }
}
